/**
 * @description 控制器
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const http = require("http")
const https = require("https")

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 增删改事件触发
  */
  emit (name, action, res) {
    if (name === 'add' && res.success) {
      let params = action.params
      // this.request({
      //   url: 'http://localhost:3601/rock/work-order/list/page?status=1',
      //   method: 'GET',
      // }).then((res) => {
      //   console.log(res)
      // })
      this.releaseMessages(params)
    }
  }

  // 发布消息
  releaseMessages (workOrder) {
    this.getAccessToken().then(token => {
      if (!token) {
        return {}
      }
      this.getSubscribeOpenids({ token }).then(openids => {
        if (openids) {
          openids.forEach(userOpenId => {
            this.sendMessages({
              userOpenId,
              token,
              data: {
                title: { value: workOrder.title },
                orderNumber: { value: workOrder.orderNumber }
              }
            })
          })
        }
      })
    })  
  }

  // 请求
  request (options) {
    if (options.url) {
      const opts = new URL(options.url)
      options.protocol = opts.protocol
      options.hostname = opts.hostname
      options.port = opts.port || /https/i.test(opts.protocol) ? 443 : 80
      options.path = opts.pathname + opts.search
    }
    let params = JSON.stringify(options.params || options.data || {})
    options.headers = options.headers || {}
    const buffer = Buffer.from(params)
    const contentLength = buffer.length
    options.headers['Content-Length'] = contentLength
    delete options.url
    delete options.params
    delete options.data
    return new Promise((resolve, reject) => {
      let httper = /https/i.test(options.protocol || options.url) ? https : http
      const req = httper.request(options, (res) => {
        this.solveRequest(res).then(subRes => {
          subRes.statusCode = res.statusCode
          let data = {
            statusCode: res.statusCode,
            data: subRes.params
          }
          resolve(data)
        })
      })
      req.on('error', (error) => {
        console.log(error)
        reject(error)
      })
      // 写入数据到请求主体
      req.write(params)
      req.end()
    })
  }

  // 获取token
  getAccessToken () {
    // 表配置
    let config = this.route.scope.CONFIG
    // 取本地
    if (this.access_token) {
      return Promise.resolve(this.access_token)
    }
    // 取服务端
    return this.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.constant.weixin.appid + '&secret=' + config.constant.weixin.appsecret,
      method: 'get'
    }).then(res => {
      // {"access_token":"ACCESS_TOKEN","expires_in":7200}
      let data = res.data || {}
      if (data.access_token) {
        this.access_token = data.access_token
        if (this.tokenTimer) {
          clearTimeout(this.tokenTimer)
        }
        this.tokenTimer = setTimeout(() => {
          this.access_token = null
        }, (data.expires_in - 20) * 1000)
      }
      return data.access_token
    })
  }

  // 获取订阅的用户列表
  getSubscribeOpenids ({ token }) {
    return this.request({
      url: 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=' + token,
      method: 'get'
    }).then(res => {
      /*
      {
        "total":2,
        "count":2,
        "data":{"openid":["OPENID1","OPENID2"]},
        "next_openid":"NEXT_OPENID"
      }
      */
      let data = res.data || {}
      let openids = data?.data?.openid
      return openids
    })
  }

  // 发布消息
  sendMessages ({userOpenId, token, data}) {
    let config = this.route.scope.CONFIG
    // 请求参数
    let params = {
      "touser": userOpenId,
      "template_id": config.constant.weixin.newWorkOrderTplId,
      "url": "http://www.daelui.com/daelbus/rock/app/dist/h5/index.html#/pages/work-order/pool",
      "topcolor": "#FF0000",
      "data": data
      /*
      {
        "title": {
          "value":"黄先生",
          "color":"#173177"
        },
        "orderNumber":{
          "value":"06月07日 19时24分",
          "color":"#173177"
        }
      }
      */
    }
    return this.request({
      url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + token,
      method: 'post',
      headers: {
        "Content-Type": "application/json;charset=utf-8"
      },
      data: params
    }).then(res => {
      /*
      {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
      }
      */
      let data = res.data || {}
      return data
    })
  }
}

module.exports = Controller